﻿using System.Diagnostics;
using Microsoft.Extensions.Logging;

namespace Dyao.Book.Core
{
    public static class LoggerExtensions
    {
        public static async Task<T> LogConsumeTimeAsync<T>(this ILogger logger, Func<Task<T>> func, string message, int overElapsedMilliseconds = 100)
        {
            var sw = Stopwatch.StartNew();

            var result = await func();

            sw.Stop();
            if (sw.ElapsedMilliseconds > overElapsedMilliseconds)
            {
                logger.LogInformation($"{message}（{sw.ElapsedMilliseconds}ms）");
            }
            return result;
        }


        public static async Task LogConsumeTimeAsync(this ILogger logger, Func<Task> func, string message, int overElapsedMilliseconds = 100)
        {
            var sw = Stopwatch.StartNew();

            await func();

            sw.Stop();
            if (sw.ElapsedMilliseconds > overElapsedMilliseconds)
            {
                logger.LogInformation($"{message}（{sw.ElapsedMilliseconds}ms）");
            }
        }
    }
}
